<?php

class BackendController extends CController
{
    public $layout = "main";
    public $data = array();
    public $connection = null;
    public $menus = array();
    public $config = array();


    public function filters()
    {
        return array(
            array('application.filter.Sessionfilter')
        );
    }

    public function init()
    {
        parent::init();
        $this->connection = Yii::app()->db;
        $this->initBasic();
    }

    public function initBasic()
    {
        $menuList = $this->connection->createCommand("select * from rk_menu where parent_id = 0 order by menu_order desc")->queryAll();
        foreach ($menuList as $menu) {
            $this->menus[$menu['menu_text']] = $menu;
            $this->menus[$menu['menu_text']]['children'] = $this->connection->createCommand("select * from rk_menu where
 parent_id = :parent_id order by menu_order desc")
                ->bindParam(":parent_id", $menu['menu_id'])
                ->queryAll();
        }

        $configlist = $this->connection->createCommand("select * from rk_config")->queryAll();
        foreach ($configlist as $item) {
            $this->config[$item['cfg_type'] . '_' . $item['cfg_key']] = $item['cfg_value'];
        }

    }

    public function run($actionID)
    {
        $transaction = $this->connection->beginTransaction();
        try {

            if (($action = $this->createAction($actionID)) !== null) {
                if (($parent = $this->getModule()) === null){
                    $parent = Yii::app();
                }
                if ($parent->beforeControllerAction($this, $action)) {
                    $this->runActionWithFilters($action, $this->filters());
                    $parent->afterControllerAction($this, $action);
                }
            } else {
                $this->missingAction($actionID);
            }
            $transaction->commit();
        } catch (Exception $e) {
//            print_r($e);exit();
            $transaction->rollback();
            $this->data['e'] = $e;
            $this->layout = "none";
            $this->render("../site/error", $this->data);
        }
    }

    public function getUser()
    {
        $userId = Yii::app()->user->getId();
        $userinfo = $this->connection->createCommand("select * from rk_user where username = :username")
            ->bindParam(":username", $userId)
            ->queryRow();
        return $userinfo;
    }

}